import {
  Keyboard,
  Model,
  ThirdPersonCamera,
  World,
  Skybox
} from "lingo3d-react"
import "./App.css"

import { useMachine } from "@xstate/react"
import poseMachine from "./stateMachines/poseMachine"
import { useRef } from "react"

const App = () => {
  const botRef = useRef<any>(null)

  const [pose, sendPose] = useMachine(poseMachine, {
    actions: {
      enterJumping: () => {
        const bot = botRef.current
        if (bot) {
          bot.velocity.y = 15
          bot.onLoop = () => {
            if (bot.velocity.y === 0) {
              bot.onLoop = undefined
              sendPose("LANDED")
            }
          }
        }
      }
    }
  })

  return (
    <World>
      {/* 天空盒 */}
      <Skybox texture={"sky.jpg"} />
      {/* 加载地形 physics =》赋予物理 */}
      <Model src="scene.gltf" scale={50} physics="map" />
      {/* 第三人称相机 */}
      <ThirdPersonCamera active mouseControl>
        {/* 加载人物模型，设置人物动画 */}
        <Model
          ref={botRef}
          physics="character"
          width={50}
          depth={50}
          src="bot.fbx"
          animations={{
            idle: "standard.fbx",
            running: "running.fbx",
            jumping: "falling.fbx"
          }}
          animation={pose.value as any}
        />
      </ThirdPersonCamera>

      <Model
        physics="character"
        width={50}
        depth={50}
        src="bot.fbx"
        x={100}
        animations={{
          gui: "gui.fbx"
        }}
        animation={"gui"}
      />

      {/* 键盘 */}
      <Keyboard
        onKeyPress={(key) => {
          if (key === "w") {
            sendPose("KEY_W_DOWN")
            const bot = botRef.current
            if (bot) bot.moveForward(-10)
          } else if (key === "Space") sendPose("KEY_SPACE_DOWN")
        }}
        onKeyUp={(key) => {
          if (key === "w") sendPose("KEY_W_UP")
        }}
      />
    </World>
  )
}

export default App
